package derk.nfc;

import java.io.IOException;

import derk.sam.DeviceNoResponseException;
import derk.sam.SerialRXTX;
import derk.sam.SerialRXTX.onReceiveDataListener;
import derk.utils.StringTool;

public class DKNfc {
	public static final byte SAM_V_FRAME_START_CODE = (byte)0xBB;         /* 扩展通讯协议帧头定义 */
	public static final byte SAM_V_INIT_COM         = (byte)0x32;   	  /* 解析服务器开始请求解析命令 */
	public static final byte SAM_V_APDU_COM         = (byte)0x33;   	  /* 解析服务器APDU命令 */
	public static final byte SAM_V_FINISH_COM       = (byte)0x34;   	  /* 解析服务器解析完成命令 */
	public static final byte SAM_V_ERROR_COM        = (byte)0x35;   	  /* 解析服务器解析错误命令 */
	public static final byte SAM_V_GET_AES_KEY_COM  = (byte)0x36;         /* 获取明文解谜密钥 */
	public static final byte RF_CLOSE_CMD           = (byte)0x18;         /* 关闭RF天线指令 */
	
	public SerialRXTX serialRXTX;
    private onReceiveNfcDataListener mOnReceiveNfcDataListener;
    public onReceiveNfcDataListener gOnReceiveNfcDataListener;
	
	/* 构造函数 */
	public DKNfc(SerialRXTX serialRXTX) {
		this.serialRXTX = serialRXTX;
		//设置串口数据监听
		this.serialRXTX.setOnReceiveDataListener(new onReceiveDataListener() {
			
			@Override
			public void OnReceiverData(String portNumberString, byte[] data) {
				// TODO Auto-generated method stub
				if ( gOnReceiveNfcDataListener != null ) {
					gOnReceiveNfcDataListener.OnReceiverNfcData(data);
				}
			}
		});
	}
	
	/* 数据回调接口 */
    public interface onReceiveNfcDataListener {
        public void OnReceiverNfcData(byte[] data);
    }
	
    /* 设置数据返回监听 */
	public void setOnReceiveNfcDataListener( onReceiveNfcDataListener l ) {
		gOnReceiveNfcDataListener = l;
	}
	
	/* 发送命令 */
	public byte[] sendCmd(byte[] cmd, int timeout) throws DeviceNoResponseException {
		return serialRXTX.sendMessageWithReturn(cmd, timeout);
	}
	public byte[] sendCmd(byte[] cmd) throws DeviceNoResponseException {
		return serialRXTX.sendMessageWithReturn(cmd);
	}
	public void sendCmdWithoutReturn(byte[] cmd) throws DeviceNoResponseException {
		try {
			serialRXTX.sendMessage(cmd);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new DeviceNoResponseException("Error: send massage error!");
		};
	}
	
	/* 发送关闭NFC天线指令 */
	public Boolean closeRf() throws DeviceNoResponseException {
		byte[] cmd = {(byte)0xAA, 0x01, RF_CLOSE_CMD};
		byte[] returnBytes = sendCmd(cmd, 100);
		if ( StringTool.byteHexToSting(returnBytes).equals("aa01fe") ) {
			
		}
		return false;
	}
}








